// pages/goos_detail/index.js
import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {}
  },

  goodsInfo: {},

  /**
   * 获取商品详情数据
  */
 getGoodsDetail(goods_id){
  // goodsObj: res.data.message
   request({url: '/goods/detail', data: {goods_id}})
   .then(res => {
     let data = res.data.message;
     this.goodsInfo = data;
     this.setData({
      goodsObj: {
        goods_name: data.goods_name,
        goods_price: data.goods_price,
        // 注意：部分iphone机型不支持识别.webp格式的图片，所以进行替换一下
        // （最好解决方式是后台全部不要将图片格式定为.webp格式）
        goods_introduce: data.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: data.pics,
      }
     });
     console.log(this.data.goodsObj);
   })
 },
  /**
   * 预览图片
  */
  handelPreviewImage(e){
    const urls = this.goodsInfo.pics.map(v => v.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls // 需要预览的图片http链接列表
    });
  },
  
  /**
   * 添加进购物车
   * (注：暂时将购物车数据放到本地缓存，实际生产版本要改成向后台发送数据并存储在服务器中，获取也是从服务器获取)
  */
  handelCartAdd(){
    console.log("add to cart");
    let cart = wx.getStorageSync("cart") || [];
    let index = cart.findIndex((val) => {return val.goods_id === this.goodsInfo.goods_id});
    console.log(index);
    if(index === -1){
      this.goodsInfo.num = 1;
      this.goodsInfo.checked = true;
      cart.push(this.goodsInfo);
    }else{
      cart[index].num++;
    }
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: "加入购物车成功",
      icon: "success",
      mask: true
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { goods_id } = options;
    // console.log(goods_id);
    this.getGoodsDetail(goods_id);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})